﻿
using HZH_Controls;
using LoLhelper.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Policy;
using System.Security.Principal;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace LoLhelper
{
    public class SendHttp
    {
        private string _baseUrl = "https://127.0.0.1:";
        private HttpClient _httpClient = new HttpClient();

        public SendHttp()
        {

        }
        //获取登录用户信息
        public async Task<User> GetUserInfo(string port, string token)
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
            string url = _baseUrl + port + "/lol-summoner/v1/current-summoner";
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
            HttpResponseMessage response = await _httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            User user = JsonSerializer.Deserialize<User>(responseBody);
            return user;

        }
        //获取头像
        public async Task<byte[]> GetImgUrlAsync(int id, string port, string token)
        {

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
            string url = _baseUrl + port + "/lol-game-data/assets/v1/profile-icons/" + id.ToString() + ".jpg";
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
            byte[] imageData = await _httpClient.GetByteArrayAsync(url);
            return imageData;

        }
        //查询是否匹配成功
        public async Task<bool> SearchMatchStatus(string port, string token)
        {
            try
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
                string url = _baseUrl + port + "/lol-lobby/v2/lobby/matchmaking/search-state";
                ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                HttpResponseMessage response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                MathStatus status = JsonSerializer.Deserialize<MathStatus>(responseBody);
                if (status.searchState == "Found")
                {
                    return true;
                }
                else return false;
            }
            catch (Exception ex)
            {
                return false;
            }

        }
        //接收对局
        public async Task<bool> AcceptGame(string port, string token)
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
            string url = _baseUrl + port + "/lol-matchmaking/v1/ready-check/accept";
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
            try
            {
                await _httpClient.PostAsync(url, null);
                return true;
            }
            catch (HttpRequestException ex)
            {
                return false;
            }
        }

        //根据名称拿到puuid
        public async Task<bool> GetPuuidAsync(string port, string token, string name)
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
            //string url = _baseUrl + port + $"/lol-summoner/v1/summoners?name={name}"; 
            string[] gameName = name.Split('#');
            string url = string.Empty;
            if (gameName.Length == 2) url = _baseUrl + port + $"/lol-summoner/v1/alias/lookup?gameName={gameName[0]}&tagLine={gameName[1]}";
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
            if (!url.IsEmpty())
            {
                HttpResponseMessage response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Puuid puuid = JsonSerializer.Deserialize<Puuid>(responseBody);
                Parm.puuid = puuid.puuid;
                return true;
            }
            return false;
        }
        //根据puuid 拿到游戏记录
        public async Task<string> GetMatches(string port, string token, string puuid)
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
            string url = _baseUrl + port + "/lol-match-history/v1/products/lol/" + $"{puuid}/matches?begIndex=0&endIndex=100";
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
            HttpResponseMessage response = await _httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }

        //获取所有英雄信息
        public async Task GetChampionInfo(string port, string token)
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
            string url = _baseUrl + port + "/lol-game-data/assets/v1/champion-summary.json";
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
            HttpResponseMessage response = await _httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            try
            {

                List<ChampionInfo> resultList = JsonSerializer.Deserialize<List<ChampionInfo>>(responseBody);
                Parm.list = resultList;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
    }
}
